package org.tp8.sampleapp.view;

import java.util.Collection;

import javax.faces.bean.ManagedProperty;

import org.apache.commons.lang.StringUtils;
import org.tp8.sampleapp.model.BaseModel;

/**
 * The Class AbstractEntityBean.
 * 
 * @param <T>
 *            the generic type
 */
public abstract class AbstractEntityBean<T extends BaseModel<Long>> extends
		AbstractBean {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -7474688931313334217L;

	/**
	 * The item.
	 */
	private T item;

	/**
	 * The id.
	 */
	@ManagedProperty("#{param.id}")
	private String id;

	/**
	 * Gets the item.
	 * 
	 * @return the item
	 */
	public T getItem() {
		// If item is empty
		if (item == null) {
			// Check if id has been specified
			if (StringUtils.isNotBlank(id)) {
				// and load
				item = findOne(Long.valueOf(id));
			} else {
				// instead create new
				item = createNew();
			}
		}
		return item;
	}

	/**
	 * Sets the item.
	 * 
	 * @param item
	 *            the new item
	 */
	public void setItem(T item) {
		this.item = item;
	}

	/**
	 * Gets the id.
	 * 
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * Sets the id.
	 * 
	 * @param id
	 *            the new id
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * Creates the new.
	 * 
	 * @return the t
	 */
	protected abstract T createNew();

	/**
	 * Find one.
	 * 
	 * @param id
	 *            the id
	 * @return the t
	 */
	protected abstract T findOne(Long id);

	/**
	 * Find all.
	 * 
	 * @return the collection
	 */
	public abstract Collection<T> findAll();

	/**
	 * Delete.
	 * 
	 * @param id
	 *            the id
	 */
	public abstract void delete(Long id);

}
